import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        carList: JSON.parse(localStorage.getItem('carList')) || [],//购物车数据
        isAds:true,//判断加减
        carNum: JSON.parse(localStorage.getItem("carList"))
        .reduce((temp,goods)=>temp+goods.num,0),//购物车数量
    },
    mutations:{
        //购物车存值
         carStore(state,goodsList){
             //判断是否存在
            let isGoods = false;
            //商品存在
            state.carList.forEach((item)=>{
                //验证商品
                if(item.typeId == goodsList.typeId && item.id == goodsList.id){
                    //判断 加 减
                    if(state.isAds){
                        item.num++;//数量+1
                    }else{
                        // 数量不能小于1
                        if(item.num <= 1){
                            item.num = 1
                        }else{
                            item.num--;//数量-1
                        }
                    }
                    item.totalPrice = (goodsList.money*item.num).toFixed(2);//总价更新
                    isGoods = true;
                }
            })
            //商品不存在
            if(!isGoods){
                //商品数量
                goodsList.num = 1;
                //商品选中状态
                goodsList.isSelect = false;
                //计算总价
                goodsList.totalPrice = (goodsList.money*goodsList.num).toFixed(2);
                //跟新carList
                state.carList.push(goodsList);
            }
            //更新本地存储
            localStorage.setItem("carList",JSON.stringify(state.carList))
            //更新商品数量
            state.carNum = JSON.parse(localStorage.getItem("carList")).reduce((temp,goods)=>temp+goods.num,0)
        }
    },
    actions:{

    }
})